package access

import (
	"context"

	"github.com/gogf/gf/v2/os/gtime"

	v1 "myapp/api/access/v1"
	"myapp/internal/model/entity"
	"myapp/internal/service"
)

// 查询角色分配菜单权限
func (c *ControllerV1) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {
	accessList, err := service.Access().GetAccessByRoleId(ctx, req.RoleId)
	if err != nil {
		return nil, err
	}
	res = &v1.GetListRes{
		Lst: accessList,
	}
	return res, nil
}
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
	id, err := service.Access().Create(ctx, &entity.Access{
		RoleId:     req.RoleId,
		MenuId:     req.MenuId,
		MenuLevel:  req.MenuLevel,
		MenuPid:    req.MenuPid,
		Module:     "",
		CreateTime: gtime.Now(),
	})
	if err != nil {
		return nil, err
	}
	res = &v1.CreateRes{Id: id}
	return res, nil
}

// 为角色分配菜单权限
func (c *ControllerV1) CreateBatch(ctx context.Context, req *v1.CreateBatchReq) (res *v1.CreateBatchRes, err error) {
	err = service.Access().CreateBatch(ctx, req.RoleId, req.MenuIds)
	if err != nil {
		return nil, err
	}
	res = &v1.CreateBatchRes{}
	return res, nil
}

func (c *ControllerV1) MemberMenu(ctx context.Context, req *v1.MemberMenuReq) (res *v1.MemberMenuRes, err error) {
	customContext := service.CustomContext().Get(ctx)
	memberId := customContext.User.Id
	role, err := service.Role().GetRoleByMember(ctx, memberId)
	if err != nil {
		return nil, err
	}
	accessList, err := service.Access().GetAccessByRoleId(ctx, role.Id)
	if err != nil {
		return nil, err
	}
	var ids []uint = make([]uint, 0, len(accessList))
	for _, access := range accessList {
		ids = append(ids, access.MenuId)
	}

	menus, err := service.AdminMenu().GetMenus(ctx, ids)
	if err != nil {
		return nil, err
	}
	res = &v1.MemberMenuRes{
		Menus: menus,
	}
	return res, nil
}
